package org.jash.document.model

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseState
import org.jash.common.mvi.BaseViewModel
import org.jash.common.net.retrofit
import org.jash.document.net.DocService
import java.io.FileOutputStream

class PdfViewModel:BaseViewModel<PdfIntent, PdfState>() {
    val service by lazy { retrofit.create(DocService::class.java) }
    fun downloadApp(down:PdfIntent.Download) {
        logDebug(down.path.absolutePath)
        if (!down.path.exists()) {
            viewModelScope.launch(Dispatchers.IO) {
                try {
                    val body = service.download(down.url)
                    val total:Long = 4 shl 20
                    body.byteStream().use { input ->
                        FileOutputStream(down.path).use { output ->
                            var length:Int
                            var buffer = ByteArray(4 shl  10)
                            var count:Long = 0;
                            while (input.read(buffer).apply { length = this } != -1) {
                                output.write(buffer, 0, length)
                                count += length
                                logDebug("count: $count, total: $total")
                            }
                        }
                    }
                    state.value = PdfState.Complete(down.path)
                } catch (e:Exception){
                    e.printStackTrace()
                    if (down.path.exists()) {
                        down.path.delete()
                    }
                    state.value = BaseState.Error(e.message ?: "")
                }
            }
        } else {
            state.value = PdfState.Complete(down.path)
        }

    }
}